package com.csist.controller;

import com.alibaba.fastjson2.JSON;
import com.csist.pojo.bo.User;
import com.csist.service.UserService;
import com.csist.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class UserServlet extends HttpServlet {
    private UserService usi = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String account = request.getParameter("username");
        String password = request.getParameter("password");
//        System.out.println(account+"\n"+password);
        Map<String,Object> map = new HashMap<>();

        //账号或密码为空且不符合规范时触发错误消息，否则执行登录操作并根据结果返回相应的消息
        if(account==null || account.trim().length()==0 || password==null || password.trim().length()==0){
            map.put("code",false);
            map.put("msg","用户名或密码不符合规范！");
        }else{
            User user = usi.login(account,password);
            if(user == null){
                map.put("code",false);
                map.put("msg","用户名或密码错误！");
            }else{
                request.getSession().setAttribute("user",user);
                map.put("code",true);
                map.put("msg","登录成功！");
            }
        }

        //判断账号和密码都不为 null 并且不为空(isEmpty() 方法来判断字符串是否为空)
//        if ((account != null && !account.trim().isEmpty()) && (password != null && !password.trim().isEmpty())) {
//            // 账号和密码不为空且符合规范的情况下
//            User user = usi.login(account,password);
//            if (user == null) {
//                map.put("code", false);
//                map.put("msg", "用户名或密码错误！");
//            } else {
//                request.getSession().setAttribute("user", user);
//                map.put("code", true);
//                map.put("msg", "登录成功！");
//            }
//        } else {
//            // 账号或密码为空或者不符合规范的情况下
//            map.put("code",false);
//            map.put("msg","账号或密码不规范");
//        }

        response.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}